package com.github.binarywang.demo.spring.handler;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.demo.spring.builder.AbstractBuilder;
import com.github.binarywang.demo.spring.builder.ImageBuilder;

import com.github.binarywang.demo.spring.dto.WxMenuKey;
import com.github.binarywang.demo.spring.service.WeixinService;

import io.renren.dao.WeixinUserDao;
import io.renren.entity.WeixinUser;
import io.renren.service.WeixinUserService;
import io.renren.utils.Config;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.builder.outxml.NewsBuilder;
import me.chanjar.weixin.mp.builder.outxml.TextBuilder;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class MenuHandler extends AbstractHandler {
	@Autowired
	private WeixinUserService weixinUserService;
	@Autowired
	private WeixinUserDao weixinUserDao;
	private Logger logger = LoggerFactory.getLogger(getClass());
	public boolean isnull(WxMpXmlMessage wxMessage){
		Map<String,Object> map= new HashMap<>();
		  wxMessage.getFromUser();
		  map.put("openid", wxMessage.getFromUser());
		           List<WeixinUser> weixinUserList=  weixinUserService.openidlist(map);
					if (weixinUserList != null && !weixinUserList.isEmpty()) {
					if(weixinUserList.get(0).getOpenid()!=null){
						return false;
					}
				}
		           
		return true;
	}
	private boolean isAdmin(WxMpXmlMessage wxMessage){
		Map<String,Object> map= new HashMap<>();
		  wxMessage.getFromUser();
		  map.put("openid", wxMessage.getFromUser());
		           List<WeixinUser> weixinUserList=  weixinUserService.openidlist(map);
		           if (weixinUserList != null && !weixinUserList.isEmpty()) {
						if(weixinUserList.get(0).getRoleid()==1){
							return true;
						}
					}
		          
		return false;
	}
  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
      Map<String, Object> context, WxMpService wxMpService,
      WxSessionManager sessionManager) {
	           
    WeixinService weixinService = (WeixinService) wxMpService;

    String key = wxMessage.getEventKey();
   logger.info("key="+key);

    try {
    	   switch (key) {
    	    case "用户公告":
    	    	return this.replyNews(wxMessage);
    	    case"用户列表":
    	    	return isAdmin(wxMessage)?userlist(wxMessage):Responsetext(wxMessage,"您不是管理员！");
    	    case"用户注册":
    	        return isnull(wxMessage)?register(wxMessage):Responsetext(wxMessage,"您已经注册过了！");
    	    default:
    	    	 return WxMpXmlOutMessage.TEXT().content("无法解析指令")
    	    	          .fromUser(wxMessage.getToUser())
    	    	          .toUser(wxMessage.getFromUser()).build();
    	    }
     
    } catch (Exception e) {
    	
      return WxMpXmlOutMessage.TEXT().content("错误异常")
          .fromUser(wxMessage.getToUser())
          .toUser(wxMessage.getFromUser()).build();
    }
    
  


 

  }

private WxMpXmlOutMessage userlist(WxMpXmlMessage wxMessage) {
	NewsBuilder newsBuilder=new NewsBuilder();
	  String testUrl = Config.getHost()+Config.getPath()+"/Weixin/lists";
	  logger.debug("host:{}", Config.getHost());
	  logger.debug("path:{}", Config.getPath());
	WxMpXmlOutNewsMessage.Item item=new WxMpXmlOutNewsMessage.Item(); 
	item.setDescription("欢迎来到用户列表界面");
	item.setPicUrl(Config.getHost()+Config.getPath()+"/statics/nnzxj.jpg");
	item.setTitle("用户列表");
	item.setUrl(testUrl);

	return newsBuilder.addArticle(item).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
}


private WxMpXmlOutNewsMessage replyNews(WxMpXmlMessage wxMessage) {
	NewsBuilder newsBuilder=new NewsBuilder();
	  String testUrl =  Config.getHost()+Config.getPath()+"/Test/index.html";
	  logger.debug("host:{}", Config.getHost());
	  logger.debug("path:{}", Config.getPath());
	WxMpXmlOutNewsMessage.Item item=new WxMpXmlOutNewsMessage.Item(); 
	item.setDescription("欢迎来到用户公告页面");
	item.setPicUrl(Config.getHost()+Config.getPath()+"/statics/nnzxj.jpg");
	item.setTitle("用户公告");
	item.setUrl(testUrl);

	return newsBuilder.addArticle(item).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
}
private WxMpXmlOutNewsMessage register(WxMpXmlMessage wxMessage) {
	
	NewsBuilder newsBuilder=new NewsBuilder();
	
	String testUrl =  Config.getHost()+Config.getPath()+"/Weixin/user.html?openid="+wxMessage.getFromUser();
	  logger.debug("host:{}", Config.getHost());
	  logger.debug("path:{}", Config.getPath());
	WxMpXmlOutNewsMessage.Item item=new WxMpXmlOutNewsMessage.Item(); 
	item.setDescription("欢迎来到注册页面");
	item.setPicUrl(Config.getHost()+Config.getPath()+"/statics/nnzxj.jpg");
	item.setTitle("注册页面");
	item.setUrl(testUrl);
	

	return newsBuilder.addArticle(item).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
}
private WxMpXmlOutTextMessage Responsetext(WxMpXmlMessage wxMessage,String str){
	TextBuilder text=new TextBuilder();
	
	return  text.content(str).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
}

}
